package com.easy.controller;

import com.easy.bean.User;
import com.easy.service.LoginService;
import com.easy.service.UserService;
import com.easy.util.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/login")
public class LoginController {

    @Autowired
    LoginService loginService;

    @Autowired
    UserService userService;

    @PostMapping("/register")
    public Result add(@RequestBody User user){
        user.setUser_password(PasswordUtil.getEncryption(user.getUser_password()));
        Object obj=userService.add(user);
        return Result.success(obj);
    }

    @GetMapping("/captcha")
    public Result captcha() {
        return Result.success(CaptchaUtil.getCaptcha());
    }

    @PostMapping("dologin")
    public Result login(User user, @RequestParam("captcha") String captcha, @RequestParam("key")String key) {
        // 验证码验证
        if (!CaptchaUtil.checkCaptcha(key, captcha)) {
            return Result.fail(500, "验证码错误");
        }
        //登陆
        try {
            String token = loginService.login( user);

            //删除验证码
            return Result.success("登陆成功",token);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail(500,e.getMessage());
        }
    }

    @GetMapping("/logininfo")
    public Result logininfo(HttpServletRequest request) {
        String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);
        User user=loginService.logininfo(token);
        return Result.success(user);
    }

    @PostMapping("/changePassword")
    public Result adminChangePassword(HttpServletRequest request,
                                      @RequestBody Map<String, String> params) {
        String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);

        // 从请求参数中获取旧密码和新密码
        String oldPassword = params.get("oldPassword");
        String newPassword = params.get("newPassword");

        if (oldPassword == null || newPassword == null) {
            return Result.fail(500, "参数错误");
        }

        try {
            // 从token中获取管理员ID
            Object idObj = TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);
            if (idObj == null) {
                return Result.fail(500, "token异常");
            }
            int adminId = Integer.parseInt(idObj.toString());

            // 调用服务层修改密码
            boolean success = loginService.changePassword(adminId, oldPassword, newPassword);
            if (success) {
                return Result.success("密码修改成功");
            } else {
                return Result.fail(500, "密码修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(500, e.getMessage());
        }
    }

}
